package cn.com.chb.dakele.net;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class Http {

	private static CloseableHttpClient client;
	private static BasicCookieStore  cookieStore;
	
	public static void setCookieStore(BasicCookieStore cookieStore) {
		Http.cookieStore = cookieStore;
	}

	public static BasicCookieStore getCookieStore() {
		return cookieStore;
	}

	public static void setClient(CloseableHttpClient c) {
		client = c;
	}

	public static CloseableHttpClient getClient() {
		if (client == null) {
			client = makeDefaultClient();
		}
		return client;
	}

	private static CloseableHttpClient makeDefaultClient() {
		
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
	    cm.setMaxTotal(200);
		cm.setDefaultMaxPerRoute(20);
		if(cookieStore == null){
			cookieStore = new BasicCookieStore();
		}
		return HttpClients.custom().setConnectionManager(cm).setDefaultCookieStore(cookieStore).build();
	}
	
	public static String getHost(String url){
		if(url==null||url.equals("")){
			return "";
		}
		String host = "";
		Pattern p =  Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
		Matcher matcher = p.matcher(url);  
		if(matcher.find()){
			host = matcher.group();  
		}
		return host;
	}
}
